<?php

namespace DebugComponent\Plugin;

class Time implements \DebugComponent\IMessagePlugin, \DebugComponent\IRenderable {

    public function  __construct() {
        $this->messages = array();
        if (self::$startTime === null) {
            self::$startTime = \microtime(true);
        }
    }

    public function setRenderer(\DebugComponent\IRenderer $renderer) {
        $this->renderer = $renderer;
    }

    public function getListenMessages() {
        return array('\DebugComponent\Message\Time');
    }

    public function write(\DebugComponent\IMessage $message) {
        if (!isset($this->messages[$message->__toString()])) {
            $this->messages[$message->__toString()] = array('count' => 1, 'time' => $message->getTimeInSecond());
        } else {
            $this->messages[$message->__toString()]['count']++;
            $this->messages[$message->__toString()]['time'] += $message->getTimeInSecond();
        }
    }

    public function getTitle() {
        return 'Time';
    }

    public function getSubtitle() {
        return \DebugComponent\Renderer\Humanize::time($this->getTotalTime()) . ' / ' . ini_get('max_execution_time') . 's';
    }

    public function render() {
        $data = new \DebugComponent\ParameterHolder();
        $data->set('messages', $this->messages);
        $data->set('title', $this->getTitle());
        $data->set('subtitle', $this->getSubtitle());
        return $this->renderer->render($data);
    }

    public static function setStartTime($time) {
        self::$startTime = $time;
    }

    public static function getStartTime() {
        return self::$startTime;
    }

    private function getTotalTime() {
        return microtime(true) - self::$startTime;
    }

    private $messages;
    private $renderer;
    private static $startTime = null;
}